import zbutils from '../utils';

export async function login_required(ctx, next){
    if(ctx.access_token && ctx.refresh_token){
        let session = await ctx.sess();
        if(!session){
            handleNoLoginRequest(ctx)
            return
        }
      
        ctx.userInfo = session;

        await next();
    }else{
       handleNoLoginRequest(ctx)
    }
}

function handleNoLoginRequest(ctx){
    ctx.clearSess && ctx.clearSess();
    if(ctx.method.toLowerCase() == "post"){
        ctx.body = {errorCode:-1,errorMessage:"未登录或登录已失效"}
        return;
    }
    ctx.throw(401)        
}


export default {login_required};
